package com.example;

import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;

import java.util.ArrayList;
import java.util.List;

public class DDLParser {
    public static TableInfo parse(String ddl) throws Exception {
        CreateTable createTable = (CreateTable) CCJSqlParserUtil.parse(ddl);
        String tableName = createTable.getTable().getName();
        List<ColumnInfo> columns = new ArrayList<>();

        for (ColumnDefinition col : createTable.getColumnDefinitions()) {
            String name = col.getColumnName();
            String type = col.getColDataType().getDataType();
            boolean isPrimaryKey = name == "id";
            String javaType = mapSqlTypeToJavaType(type);
            String javaName = toCamelCase(name);
            List<String> columnSpecsList = col.getColumnSpecs();
            String comment = columnSpecsList.get(columnSpecsList.size()-1);
            comment = comment.replaceAll("'","");
            columns.add(new ColumnInfo(name, type, isPrimaryKey, javaType, javaName, comment));
        }
        String tableComment = createTable.getTableOptionsStrings().get(createTable.getTableOptionsStrings().size()-1);

        return new TableInfo(tableName, toCamelCase(tableName), columns,tableComment);
    }

    private static String mapSqlTypeToJavaType(String sqlType) {
        sqlType = sqlType.toLowerCase();
        if (sqlType.contains("bigint")) {
            return "Long";
        } else if (sqlType.contains("int")) {
            return "Integer";
        } else if (sqlType.contains("bit")) {
            return "Integer";
        } else if (sqlType.contains("varchar") || sqlType.contains("text")) {
            return "String";
        } else if (sqlType.contains("datetime") || sqlType.contains("timestamp")) {
            return "java.util.Date";
        } else if (sqlType.contains("decimal") || sqlType.contains("numeric")) {
            return "java.math.BigDecimal";
        } else if (sqlType.contains("tinyint") ) {
            return "Integer";
        }
        else if (sqlType.contains("bit")) {
            return "Boolean";
        }
        // 可以根据需要添加更多的类型映射
        return "Object";
    }

    private static String toCamelCase(String s) {
        String[] parts = s.split("_");
        StringBuilder camelCaseString = new StringBuilder(parts[0].toLowerCase());
        for (int i = 1; i < parts.length; i++) {
            camelCaseString.append(Character.toUpperCase(parts[i].charAt(0)))
                    .append(parts[i].substring(1).toLowerCase());
        }
        String javaName = camelCaseString.toString();

        return javaName.replaceAll("`","");
    }
}